package com.thinkersre.quartz;

import com.thinkersre.entity.DiscussPost;
import com.thinkersre.service.DiscussPostService;
import com.thinkersre.service.ElasticsearchService;
import com.thinkersre.service.LikeService;
import com.thinkersre.util.RedisKeyUtil;
import com.thinkersre.util.ThinkersReConstant;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PostScoreRefreshJob implements Job, ThinkersReConstant {
        private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
        @Resource
        private RedisTemplate redisTemplate;
        @Resource
        private DiscussPostService discussPostService;
        @Resource
        private LikeService likeService;
        @Resource
        private ElasticsearchService elasticsearchService;
        //Thinkers创建时间
        private static final Date ThinkersBuildTime;
        static{
                try {
                        ThinkersBuildTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-5-10 00:00:00");
                } catch (ParseException e) {
                        throw new RuntimeException("初始化Thinkers创建时间失败。",e);
                }
        }
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                String redisKey = RedisKeyUtil.getPostScoreKey();
                BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(redisKey);
                if(boundSetOperations.size() == 0){
                        logger.info("[任务取消] 没有需要刷新的帖子。");
                        return;
                }
                logger.info("[任务开始] 正在刷新帖子分数:"+boundSetOperations.size());
                while (boundSetOperations.size()>0){
                        this.refresh((Integer)boundSetOperations.pop());
                }
                logger.info("[任务结束] 帖子分数刷新完毕.");
    }

    private void refresh(int postId){
            DiscussPost discussPost = discussPostService.findDiscusPostById(postId);
            if (discussPost == null){
                    logger.error("该帖子不存在:id = "+postId);
                    return;
            }
            //是否精华
            boolean wonderful = discussPost.getStatus() == 1;
            //评论数量
            int commentCount = discussPost.getCommentCount();
            //点赞数量
            long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,postId);


            //计算权重
            double w = (wonderful ? 75 : 0 ) + commentCount * 10 +likeCount * 2;
            //分数 = 帖子权重+距离天数
            double score = Math.log(Math.max(w,1)) + (discussPost.getCreateTime().getTime() - ThinkersBuildTime.getTime())/(1000 * 3600 * 24);
            //更新帖子分数
            discussPostService.updateScore(postId,score);
            //同步搜索数据
            discussPost.setScore(score);
            elasticsearchService.saveDiscussPost(discussPost);

        }
}
